<template>
  <div class="pagebox">
    <crumbs @goBack="goBack" :superiorMenu="['生产设置']" currentMenu="生产流程" style="margin-bottom: 12px"></crumbs>
    <a-card :bordered="false" size="small">
      <div class="topBox">
        <div>
          <a-button @click="handleShowFilter" icon="filter"
            >筛选 <span class="filter-num" style="margin-left: 5px">{{ ' ' + filteredNums() }}</span></a-button
          >
          <a-button @click="showColumn" icon="unordered-list" style="margin-left: 10px"> 设置列 </a-button>
        </div>
        <div style="display: flex">
          <PubImport
            @updateParentData="updateParentData"
            ref="PubImport"
            tableCode="MESS_PRODUCT_FLOW"
            modelName="生产流程导入模板"
            style="margin-right: 10px"
          />
          <PubExport
            :exportUrl="exportUrl"
            :columns="columns"
            :propForm="formatData()"
            :selectedRows="chooseArr"
            :sortForm="sortForm"
            :fullName="fullName"
            style="margin-right: 10px"
          />
          <!-- <a-button style="margin-right: 10px">导入</a-button> -->
          <a-button type="primary" @click="add"> +新建 </a-button>
        </div>
      </div>
      <a-table
        row-key="id"
        :key="tableKey"
        :columns="columns"
        :data-source="tableData"
        :pagination="false"
        :scroll="{ x: scrollX, y: 'calc(100vh - 366px)' }"
        :row-selection="{ selectedRowKeys: selectedRowKeys, columnTitle: ' ', onChange: onSelectChange }"
        @change="handleChange"
        :components="drag(columns, 'PRODUCTION_PROCESS')"
      >
        <span slot="flowName" :title="text" slot-scope="text">
          {{ text }}
        </span>
        <span slot="processRequire" :title="text" slot-scope="text">
          {{ text }}
        </span>
        <span slot="remark" :title="text" slot-scope="text">
          {{ text }}
        </span>
        <!-- 输入框搜索 -->
        <div slot="searchInput" slot-scope="{ selectedKeys, confirm, clearFilters, column }" class="searchWorkOreder">
          <a-input
            placeholder="请输入"
            v-model="filterForm[column.dataIndex]"
            style="width: 188px; display: block"
            @pressEnter="handleSearch"
          />
          <a-button
            type="primary"
            style="width: 80px; margin-left: 20px; display: block"
            @click="() => handleSearch(selectedKeys, confirm, column.dataIndex, clearFilters)"
          >
            搜索
          </a-button>
        </div>
        <a-icon
          slot="searchIcon"
          slot-scope="filtered"
          type="search"
          :style="{ color: filtered ? '#108ee9' : undefined }"
        />
        <span
          slot="flowCode"
          :title="record.flowCode"
          slot-scope="text, record"
          class="btn-text"
          @click="handleDetail(record)"
        >
          {{ record.flowCode }}
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleDelete(record)" href="#">删除</a>
        </span>
      </a-table>
    </a-card>
    <div
      class="uni-card resetPadding"
      :style="{
        position: 'fixed',
        bottom: 0,
        right: 0,
        zIndex: 2,
        left: collapsed ? '79px' : '208px',
        background: '#fff',
        paddingLeft: '43px',
      }"
    >
      <div style="display: inline-block">
        <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>
        <span style="margin-left: 8px">
          {{ `已选 ${selectedRowKeys.length}/${total} 项` }}
          <span @click="clearArr" class="pubColor" style="margin: 0 10px">清空</span>
          <span @click="handleDelete(selectedRowKeys)" class="pubColor" style="margin: 0 10px">删除</span>
        </span>
      </div>
      <div style="display: inline-block; float: right">
        <a-pagination
          :total="total"
          v-model="current"
          :page-size-options="pageSizeOptions"
          :page-size="pageSize"
          @change="onChangePage"
          @showSizeChange="onShowSizeChange"
          show-quick-jumper
          show-size-changer
        />
      </div>
    </div>
    <SetColumn
      columnName="设置列"
      ref="SetColumn"
      v-if="showSetColumn"
      @sureBtn="sureBtn"
      @cancelBtn="showSetColumn = false"
    />
    <a-drawer placement="right" width="500" :visible="showFilter" @close="closeFilter">
      <div class="filter-body">
        <div slot="title" class="uni-card filter-tit">
          筛选 <span class="filter-num">{{ filteredNums(1) }}</span>
        </div>
        <div class="uni-card" v-if="filteredNums(1) > 0" style="background: #fff">
          <div v-for="(item, i) in filteredList" :key="i" v-show="item.text" class="tag-wrap">
            <span class="filter-tag" @click="delFiltered(item.key)">
              <span class="tag-text">{{ `${item.title}：${item.text}` }}</span>
              <a-icon type="close" style="float: right" />
            </span>
          </div>
        </div>
        <div style="overflow-y: scroll; flex: 1; padding: 0">
          <div class="uni-card" style="background: #fff">
            <a-form-model ref="ruleForm" layout="vertical" :model="filterForm">
              <a-form-model-item label="流程编号">
                <a-input v-model="filterForm.flowCode" placeholder="请输入" :maxLength="30" />
              </a-form-model-item>
              <a-form-model-item label="流程名称">
                <a-input v-model="filterForm.flowName" placeholder="请输入" :maxLength="30" />
              </a-form-model-item>
              <a-form-model-item label="组成工序">
                <a-input v-model="filterForm.process" placeholder="请输入" />
              </a-form-model-item>
            </a-form-model>
          </div>
        </div>
        <div class="footer-submit">
          <a-button class="margin-btn" @click="resetFilter">重置</a-button>
          <a-button type="primary" @click="handleFilter">确定</a-button>
        </div>
      </div>
    </a-drawer>
    <windowDetail ref="windowDetail"></windowDetail>
    <windowForm ref="windowForm" @refresh="handleSearch"></windowForm>
  </div>
</template>
<script>
import SetColumn from '@/pubComponent/SetColumn.vue'
import { getNewColumns, subStrText, camelCase2UnderLine, objArrFilter } from '@/utils/util'
import { messProductFlowList, messProductFlowDel, messProductFlowDelBatch } from '@/api/goodsManagement'
import crumbs from '@/components/crumbs.vue'
import { mapState } from 'vuex'
import PubImport from '@/components/pubBtn/PubImport.vue'
import PubExport from '@/components/pubBtn/PubExport.vue'
import moment from 'moment'
import tableDragResize from '@/mixins/tableDragResize'
import windowDetail from './productionProcessDetail.vue'
import windowForm from './productionProcessForm.vue'

/* 打开设置列面板123 */
const columnsValue = [
  {
    title: '流程编号',
    dataIndex: 'flowCode',
    ellipsis: true,
    width: 180,
    key: 'flowCode',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'flowCode',
    },
  },
  {
    title: '流程名称',
    dataIndex: 'flowName',
    key: 'flowName',
    width: 180,
    ellipsis: true,
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'flowName',
    },
  },
  {
    title: '组成工序',
    dataIndex: 'process',
    width: 180,
    key: 'process',
    ellipsis: true,
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'flowName',
    },
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    width: 180,
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
    sorter: true,
    ellipsis: true,
  },
  {
    title: '创建人',
    dataIndex: 'createByText',
    width: 180,
    key: 'createByText',
    ellipsis: true,
  },
]
const actionArr = [
  {
    fixed: 'right',
    title: '操作',
    width: 110,
    dataIndex: 'action',
    align: 'left',
    scopedSlots: { customRender: 'action' },
  },
]
export default {
  name: 'workProcessList', //生产流程列表
  components: { crumbs, SetColumn, PubImport, PubExport, windowDetail, windowForm },
  mixins: [tableDragResize],
  data() {
    return {
      subStrText,
      tableData: [],
      selectedRowKeys: [],
      selectArr: [],
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      current: 1,
      total: 100,
      pageSize: 10,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      showSetColumn: false,
      // 排序
      sortForm: {
        sortType: '',
        sortColumn: '',
      },
      showFilter: false, // 筛选抽屉
      // 筛选form
      filterForm: {
        flowCode: '', //流程编号
        flowName: '', //流程名称
        process: '', //组成工序
      },
      filteredFormLable: {
        flowCode: '流程编号', //流程编号
        flowName: '流程名称', //流程名称
        process: '组成工序', //组成工序
      },
      columns: [
        {
          title: '流程编号',
          dataIndex: 'flowCode',
          width: 180,
          ellipsis: true,
          key: 'flowCode',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'flowCode',
          },
        },
        {
          title: '流程名称',
          dataIndex: 'flowName',
          key: 'flowName',
          width: 180,
          ellipsis: true,
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'flowName',
          },
        },
        {
          title: '组成工序',
          dataIndex: 'process',
          width: 180,
          key: 'process',
          ellipsis: true,
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'flowName',
          },
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
          width: 180,
          sorter: true,
          ellipsis: true,
        },
        {
          title: '创建人',
          dataIndex: 'createByText',
          width: 180,
          key: 'createByText',
          ellipsis: true,
        },
        // {
        //   fixed: 'right',
        //   title: '操作',
        //   width: 110,
        //   dataIndex: 'action',
        //   // align: 'center',
        //   scopedSlots: { customRender: 'action' },
        // },
      ],
      // 导出参数
      exportUrl: '/prodset/messProductFlow/exportXls',
      chooseArr: [],
      allRequestList: [],
      fullName: `生产流程 ${moment(new Date()).format('YYYY-MM-DD HH:mm')}`,
      tableKey: 1.9,
      sessionParams: {},
    }
  },
  computed: {
    scrollX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum
    },
    ...mapState({
      collapsed: (state) => state.user.collapsed,
    }),
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    filteredList() {
      let list = []
      for (let key in this.filterForm) {
        list.push({
          title: this.filteredFormLable[key],
          text: this.filterForm[key],
          key,
        })
      }
      return list
    },
  },
  created() {
    let sessionObj = sessionStorage.getItem(`${this.BUSI_CONST.Entity.PRODUCTION_PROCESS}filter`)
    if (sessionObj) {
      let obj = JSON.parse(sessionObj)
      this.filterForm = obj.filterForm
      this.sortForm = obj.sortForm
      this.current = obj.current
      this.pageSize = obj.pageSize
    }
    this.initData()
    this.requestData()
  },
  beforeRouteLeave(to, from, next) {
    if (to.path != '/skillManagement/productionProcessForm' || JSON.stringify(to.query) == '{}') {
      sessionStorage.removeItem(`${this.BUSI_CONST.Entity.PRODUCTION_PROCESS}filter`)
    }
    next()
  },
  methods: {
    //更新父组件页面
    updateParentData() {
      this.handleSearch()
    },
    /* 删除、批量删除 */
    handleDelete(v) {
      if (v instanceof Array) {
        if (v.length > 0) {
          console.log(v.toString())
          let that = this
          that.$antdConfirm({
            title: '确定要删除流程吗?',
            content: `共选中${v.length}条生产流程`,
            onOk() {
              messProductFlowDelBatch({ ids: v.toString() }).then((res) => {
                if (res.code == 200) {
                  that.$antdMessage.success('生产流程删除成功！')
                  that.handleSearch()
                  that.clearArr()
                } else {
                  that.$antdMessage.error(res.message)
                }
              })
            },
            onCancel() {},
          })
        } else {
          this.$antdMessage.warning('请勾选需要批量删除的数据')
        }
      } else {
        let that = this
        that.$antdConfirm({
          title: '确定要删除此生产流程吗?',
          content: ``,
          onOk() {
            messProductFlowDel({ id: v.id }).then((res) => {
              if (res.code == 200) {
                that.$antdMessage.success('生产流程删除成功！')
                if (that.tableData.length === 1) {
                  that.current = that.current == 1 ? 1 : that.current - 1
                }
                that.requestData()
                that.clearArr()
              } else {
                that.$antdMessage.error(res.message)
              }
            })
          },
          onCancel() {},
        })
      }
    },
    /* 编辑 */
    handleEdit(v) {
      sessionStorage.setItem(`${this.BUSI_CONST.Entity.PRODUCTION_PROCESS}filter`, JSON.stringify(this.sessionParams))
      this.$refs.windowForm.initForm(v.id)
    },
    // 详情
    handleDetail(v) {
      this.$refs.windowDetail.initDetail(v.id)
    },
    // 加载数据
    initData() {
      /* 设置列 */
      var oldValue = localStorage.getItem(this.BUSI_CONST.Entity.PRODUCTION_PROCESS)
      this.columns = getNewColumns(columnsValue, JSON.parse(oldValue), actionArr, this.columns)
    },
    formatData() {
      /* 请求列表数据 */
      let parameter = {
        ...this.filterForm,
        pageNo: this.current,
        pageSize: this.pageSize,
      }
      return parameter
    },
    requestData() {
      /* 请求列表数据 */
      let parameter = {
        ...this.filterForm,
        pageNo: this.current,
        pageSize: this.pageSize,
        ...this.sortForm,
      }

      this.sessionParams = {
        filterForm: this.filterForm,
        sortForm: this.sortForm,
        current: this.current,
        pageSize: this.pageSize,
      }
      messProductFlowList(parameter).then((res) => {
        if (res.code == 200) {
          this.tableData = res.result.records
          this.total = res.result.total
          this.allRequestList = this.allRequestList.concat(this.tableData)
          this.allRequestList = objArrFilter(this.allRequestList)
          console.log(this.tableData, 'this.tableData')
        }
      })
    },
    // 导航栏
    goBack() {},
    // 点击新建按钮
    add() {
      this.$refs.windowForm.initForm()
    },

    handleSearch(selectedKeys, confirm, dataIndex, clearFilters) {
      // confirm() //用来关闭搜索弹窗
      // clearFilters() //用来重置搜索内容
      // console.log('这都是啥00：', selectedKeys)
      // console.log('这都是啥11：', confirm)
      // console.log('这都是啥22：', dataIndex)
      // console.log('这都是啥33：', clearFilters)
      this.current = 1
      this.requestData()
    },
    /* 打开筛选 */
    handleShowFilter() {
      this.showFilter = true
    },
    /* 关闭筛选 */
    closeFilter() {
      this.showFilter = false
    },
    /* 确定筛选 */
    handleFilter() {
      this.handleSearch()
      this.showFilter = false
    },
    /* 删除已选 */
    delFiltered(key) {
      this.filterForm[key] = ''
    },
    /* 重置筛选 */
    resetFilter() {
      this.filterForm = {
        flowCode: '', //流程编号
        flowName: '', //流程名称
        process: '', //组成工序
      }
      this.handleSearch()
    },
    filteredNums(n) {
      let nums = 0
      if (n) {
        for (let key in this.filterForm) {
          if (this.filterForm[key] != '' && key != 'createByText') {
            nums += 1
          }
        }
      } else {
        for (let key in this.filterForm) {
          if (this.filterForm[key] != '') {
            nums += 1
          }
        }
      }
      return nums
    },
    /* 打开设置列面板123 */
    showColumn() {
      this.showSetColumn = true
      this.$nextTick(() => {
        this.$refs.SetColumn.paramsData(columnsValue, this.BUSI_CONST.Entity.PRODUCTION_PROCESS, this.columns)
      })
    },
    /* 设置列 */
    sureBtn(emitArr) {
      this.columns = getNewColumns(columnsValue, emitArr, actionArr)
      console.log(this.columns)
      localStorage.setItem(this.BUSI_CONST.Entity.PRODUCTION_PROCESS, JSON.stringify(emitArr))
      this.tableKey += 1
    },
    // table
    // table
    // 排序
    handleChange(pagination, filters, sorter, { currentDataSource }) {
      console.log('看看这是啥33：', sorter)
      if (sorter.order) {
        let sortType = ''
        if (sorter.order == 'ascend') {
          sortType = 'ASC'
        } else {
          sortType = 'DESC'
        }
        this.sortForm = {
          sortType: sortType,
          sortColumn: camelCase2UnderLine(sorter.columnKey),
        }
        this.requestData()
      } else {
        this.sortForm = {
          sortType: '',
          sortColumn: '',
        }
        this.requestData()
      }
    },
    // table选择
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.chooseArr = []
      for (let tag of selectedRowKeys) {
        for (let item of this.allRequestList) {
          if (tag == item.id) {
            this.chooseArr.push(item)
          }
        }
      }
      this.checkBoxStatus()
    },
    // 全选
    onCheckAllChange(e) {
      console.log('zhehsig', e.target)
      if (e.target.checked) {
        for (let item of this.tableData) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.chooseArr = this.chooseArr.filter((every) => {
            return every.id != item.id
          })
          this.selectedRowKeys.push(item.id)
          this.chooseArr.push(item)
        }
      } else {
        for (let item of this.tableData) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.chooseArr = this.chooseArr.filter((every) => {
            return every.id != item.id
          })
        }
      }
      this.checkBoxStatus()
    },
    // 清空
    clearArr() {
      this.selectedRowKeys = []
      this.chooseArr = []
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.tableData) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        console.log()
        console.log('第一个参数是；', checkValue)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    // 分页
    onChangePage(current, pageSize) {
      console.log(current, pageSize, '123123')
      this.current = current
      this.requestData()
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize
      this.current = current
      this.requestData()
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
.table-operations {
  margin-bottom: 16px;
}

.table-operations > button {
  margin-right: 8px;
}
.topBox {
  .flex(space-between, center);
  margin-bottom: 16px;
}
.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
.pubColor {
  font-size: 14px;
  color: #1890ff;
  cursor: pointer;
}
.pagebox {
  /deep/ .ant-card-body {
    height: calc(100vh - 226px);
    overflow: hidden;
    padding: 20px 16px;
  }
}
.header {
  width: 150%;
  margin: -12px -12px @distance4;
}
.backBox {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .backC {
    cursor: pointer;
    display: flex;
    align-items: center;
  }
}
.j-table-force-nowrap {
  margin-top: @distance1;
}
.btns {
  margin-left: @distance5;
}
.right-btn {
  float: right;
  display: flex;
  justify-content: flex-end;
}
.mg-left {
  margin-left: @distance3;
}
.filter-tit {
  background: #fff;
  border-bottom: 1px solid @greyBorder;
  font-size: @fontSize4;
}
.filter-num {
  color: @normalFont;
}
.filter-body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.margin-btn {
  margin-right: @distance5;
}
.filter-tag {
  display: inline-block;
  position: relative;
  padding: 8px 10px;
  border-radius: 4px;
  font-size: @fontSize1;
  line-height: @fontSize1;
  max-width: 100%;
  background: @greyBg;
  color: @titFont;
  cursor: pointer;
  .tag-text {
    display: inline-block;
    padding-right: 20px;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .anticon-close {
    position: absolute;
    right: 8px;
    top: 8px;
  }
}
.tag-wrap:nth-of-type(n + 2) {
  margin-top: 10px;
}
</style>
